package codeTop;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class q105 {
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        Map<Integer,Integer> map = new HashMap<>();
        for (int i = 0; i < inorder.length; i++) {
            map.put(inorder[i],i);
        }
        return dfs(preorder,0,inorder.length-1,map);
    }
    int idx = 0;
    private TreeNode dfs(int[] preorder, int l, int r,Map<Integer,Integer> map) {
        if (l > r) {
            return null;
        }
        int val = preorder[idx++];
        TreeNode node = new TreeNode(val);
        Integer pos = map.get(val);
        node.left = dfs(preorder,l,pos-1,map);
        node.right = dfs(preorder,pos+1,r,map);
        return node;
    }


}
